"use client";
import {listQuestionByPageUsingPost, listQuestionVoByPageUsingPost} from "@/api/questionController";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { ProTable } from "@ant-design/pro-components";
import React, { useRef, useState } from "react";
import TagList from "@/components/TagList";
import Link from "next/link";

interface Props {
  defaultQuestions?: API.QuestionVO[];
  defaultTotal?: number;
  defaultSearchParams?: API.QuestionQueryRequest;
}

/**
 * 题目列表页面
 *
 * @constructor
 */
const QuestionTable: React.FC = (props: Props) => {
  const actionRef = useRef<ActionType>();
  // 题目列表
  const {
    defaultQuestions = [],
    defaultTotal,
    defaultSearchParams = {},
  } = props;

  const [questionList, setQuestionList] = useState<API.QuestionVO[]>(
    defaultQuestions || [],
  );
  // 题目总数
  const [total, setTotal] = useState<number>(defaultTotal || 0);

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.Question>[] = [
    {
      title: "标题",
      dataIndex: "title",
      valueType: "text",
      render(_, record) {
        return <Link href={`/question/${record.id}`}>{record.title}</Link>;
      },
    },

    {
      title: "标签",
      dataIndex: "tagList",
      valueType: "select",
      width:"20%",
      fieldProps: {
        mode: "tags",
      },
      render: (_, record) => {
        return <TagList tagList={record.tagList} />;
      },
    },
  ];
  return (
    <div className="question-table">
      <ProTable<API.Question>
        actionRef={actionRef}
        size="middle"
        search={{
          labelWidth: "auto",
        }}
        form={{
          initialValues:defaultSearchParams,
        }}
        request={async (params, sort, filter) => {
          // 设置默认的每页记录数
          const defaultPageSize = 10;
          // 如果params中未提供pageSize，则使用默认值
          const pageSize = defaultPageSize;
          // 设置params中的pageSize以确保每页显示10条记录
          params.pageSize = pageSize;
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;

          // @ts-ignore
          const { data, code } = await listQuestionVoByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.QuestionQueryRequest);

          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
    </div>
  );
};
export default QuestionTable;
